const express = require('express');
const cors = require('cors');
const mysql = require('mysql2/promise');
const bcrypt = require('bcryptjs');

const app = express();

// 1. 基础中间件
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 2. CORS 配置
app.use(cors({
  origin: '*',
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization']
}));

// 3. 请求日志中间件
app.use((req, res, next) => {
  console.log('----------------------------------------');
  console.log(`${new Date().toISOString()} - ${req.method} ${req.url}`);
  console.log('请求头:', JSON.stringify(req.headers, null, 2));
  console.log('请求体:', JSON.stringify(req.body, null, 2));
  console.log('----------------------------------------');
  next();
});

// 4. 数据库连接池
const pool = mysql.createPool({
  host: 'localhost',
  user: 'root',
  password: '123456',
  database: 'movie_recommendation',
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
});

// 5. 测试数据库连接
pool.getConnection()
  .then(connection => {
    console.log('数据库连接成功');
    connection.release();
  })
  .catch(err => {
    console.error('数据库连接失败:', err);
  });

// 6. API 路由
// 6.1 用户注册
app.post('/api/register', async (req, res) => {
  try {
    console.log('处理注册请求:', req.body);
    const { username, password } = req.body;

    if (!username || !password) {
      console.log('用户名或密码为空');
      return res.status(400).json({ error: '用户名和密码不能为空' });
    }

    // 检查用户名是否已存在
    const [existingUsers] = await pool.execute(
      'SELECT id, username, password FROM users WHERE username = ?',
      [username]
    );

    if (existingUsers.length > 0) {
      console.log('用户名已存在');
      return res.status(409).json({ error: '用户名已存在' });
    }

    // 对密码进行哈希处理
    const hashedPassword = await bcrypt.hash(password, 10);
    const [result] = await pool.execute(
      'INSERT INTO users (username, password) VALUES (?, ?)',
      [username, hashedPassword]
    );

    console.log('注册成功:', result);
    res.status(201).json({ message: '注册成功' });
  } catch (error) {
    console.error('注册失败:', error);
    res.status(500).json({ error: '注册失败' });
  }
});

// 6.2 用户登录
app.post('/api/login', async (req, res) => {
  try {
    console.log('处理登录请求:', req.body);
    const { username, password } = req.body;

    if (!username || !password) {
      console.log('用户名或密码为空');
      return res.status(400).json({ error: '用户名和密码不能为空' });
    }

    // 查询用户
    const [users] = await pool.execute(
      'SELECT id, username, password FROM users WHERE username = ?',
      [username]
    );

    console.log('查询结果:', users);

    if (users.length === 0) {
      console.log('用户不存在');
      return res.status(401).json({ error: '用户名或密码错误' });
    }

    // 验证密码
    const isPasswordValid = await bcrypt.compare(password, users[0].password);
    console.log('密码验证:', { isPasswordValid });

    if (!isPasswordValid) {
      console.log('密码错误');
      return res.status(401).json({ error: '用户名或密码错误' });
    }

    // 登录成功
    const response = {
      message: '登录成功',
      user: {
        id: users[0].id,
        username: users[0].username
      }
    };
    console.log('登录成功:', response);
    res.json(response);
  } catch (error) {
    console.error('登录失败:', error);
    res.status(500).json({ error: '登录失败' });
  }
});

// 6.3 调试接口
app.get('/api/debug/users', async (req, res) => {
  try {
    const [users] = await pool.execute('SELECT id, username, password FROM users');
    res.json(users);
  } catch (error) {
    console.error('获取用户列表失败:', error);
    res.status(500).json({ error: '获取用户列表失败' });
  }
});

// 6.4 添加电影 (管理员接口)
app.post('/api/admin/movies', async (req, res) => {
  try {
    console.log('处理添加电影请求:', req.body);
    const {
      title,
      image_url,
      director,
      cast,
      genres,
      description,
      release_date,
      average_rating,
      duration
    } = req.body;

    if (!title || !image_url || !director || !cast || !genres || !description || !release_date || !average_rating || !duration) {
      console.log('缺少必填字段');
      return res.status(400).json({ error: '所有字段都是必填项' });
    }

    const [result] = await pool.execute(
      `INSERT INTO movies (title, image_url, director, cast, genres, description, release_date, average_rating, duration)
       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
      [title, image_url, director, cast, genres, description, release_date, average_rating, duration]
    );

    console.log('电影添加成功:', result);
    res.status(201).json({ message: '电影添加成功', movieId: result.insertId });
  } catch (error) {
    console.error('添加电影失败:', error);
    res.status(500).json({ error: '添加电影失败', details: error.message });
  }
});

// 6.5 获取电影列表
app.get('/api/movies', async (req, res) => {
  try {
    console.log('处理获取电影列表请求:', req.query);
    const start = parseInt(req.query.start) || 0;
    const count = parseInt(req.query.count) || 20;

    const [movies] = await pool.execute(
      `SELECT * FROM movies ORDER BY id DESC LIMIT ${count} OFFSET ${start}`
    );

    console.log('server/app.js - 原始数据库查询结果 movies:', movies);

    // 格式化电影数据
    const formattedMovies = movies.map(movie => ({
      id: movie.id,
      title: movie.title,
      original_title: movie.original_title,
      images: {
        large: movie.image_url
      },
      rating: {
        average: parseFloat(movie.average_rating)
      },
      directors: movie.director.split('，').map(d => ({ name: d.trim() })),
      casts: movie.cast.split('，').map(c => ({ name: c.trim() })),
      genres: String(movie.genres || '').split('，'),
      year: movie.release_date.split('-')[0],
      summary: movie.summary
    }));

    console.log(`成功获取 ${formattedMovies.length} 部电影`);
    res.json(formattedMovies);
  } catch (error) {
    console.error('获取电影列表失败:', error);
    res.status(500).json({ error: '获取电影列表失败', details: error.message });
  }
});

// 6.6 获取单个电影详情
app.get('/api/movies/:id', async (req, res) => {
  try {
    const { id } = req.params;
    console.log(`处理获取电影详情请求，ID: ${id}`);

    const [movies] = await pool.execute(
      'SELECT * FROM movies WHERE id = ?',
      [id]
    );

    if (movies.length === 0) {
      console.log(`电影 ID ${id} 未找到`);
      return res.status(404).json({ error: '电影未找到' });
    }

    const movie = movies[0];

    // 格式化电影数据以匹配前端期望的格式
    const formattedMovie = {
      id: movie.id,
      title: movie.title,
      original_title: movie.original_title,
      images: {
        large: movie.image_url || ''
      },
      rating: {
        average: parseFloat(movie.average_rating) || 0,
        stars: (parseFloat(movie.average_rating) * 5).toFixed(0)
      },
      directors: movie.director ? movie.director.split('，').map(d => ({ name: d.trim() })) : [],
      casts: movie.cast ? movie.cast.split('，').map(c => ({ name: c.trim() })) : [],
      genres: String(movie.genres || '').split('，'),
      year: movie.release_date ? movie.release_date.substring(0, 4) : '',
      summary: movie.summary,
      countries: [], // 如果数据库中没有，可以留空或添加默认值
      durations: movie.duration ? [movie.duration] : []
    };

    console.log(`成功获取电影详情: ${movie.title}`);
    res.json(formattedMovie);
  } catch (error) {
    console.error('获取电影详情失败:', error);
    res.status(500).json({ error: '获取电影详情失败', details: error.message });
  }
});

// 6.7 获取待映电影列表
app.get('/api/coming_soon', async (req, res) => {
  try {
    console.log('处理获取待映电影列表请求:', req.query);
    const start = parseInt(req.query.start) || 0;
    const count = parseInt(req.query.count) || 20;

    const [movies] = await pool.execute(
      `SELECT * FROM coming_soon ORDER BY release_date ASC LIMIT ${count} OFFSET ${start}`
    );

    // 格式化电影数据
    const formattedMovies = movies.map(movie => ({
      id: movie.id,
      title: movie.title,
      original_title: movie.original_title,
      images: {
        large: movie.image_url
      },
      directors: movie.director ? movie.director.split('，').map(d => ({ name: d.trim() })) : [],
      casts: movie.cast ? movie.cast.split('，').map(c => ({ name: c.trim() })) : [],
      genres: String(movie.genres || '').split('，'),
      year: movie.release_date
        ? (movie.release_date instanceof Date
          ? movie.release_date.getFullYear().toString()
          : String(movie.release_date).split('-')[0])
        : '',
      summary: movie.description,
      wish_count: movie.wish_count
    }));

    console.log(`成功获取 ${formattedMovies.length} 部待映电影`);
    res.json(formattedMovies);
  } catch (error) {
    console.error('获取待映电影列表失败:', error);
    res.status(500).json({ error: '获取待映电影列表失败', details: error.message });
  }
});

// 6.8 获取单个待映电影详情
app.get('/api/coming_soon/:id', async (req, res) => {
  try {
    const { id } = req.params;
    console.log(`处理获取待映电影详情请求，ID: ${id}`);

    const [movies] = await pool.execute(
      'SELECT * FROM coming_soon WHERE id = ?',
      [id]
    );

    if (movies.length === 0) {
      console.log(`待映电影 ID ${id} 未找到`);
      return res.status(404).json({ error: '待映电影未找到' });
    }

    const movie = movies[0];

    // 格式化电影数据以匹配前端期望的格式
    const formattedMovie = {
      id: movie.id,
      title: movie.title,
      original_title: movie.original_title,
      images: {
        large: movie.image_url || ''
      },
      directors: movie.director ? movie.director.split('，').map(d => ({ name: d.trim() })) : [],
      casts: movie.cast ? movie.cast.split('，').map(c => ({ name: c.trim() })) : [],
      genres: String(movie.genres || '').split('，'),
      year: movie.release_date
        ? (movie.release_date instanceof Date
          ? movie.release_date.getFullYear().toString()
          : String(movie.release_date).split('-')[0])
        : '',
      summary: movie.description,
      wish_count: movie.wish_count,
      countries: [], // 如果数据库中没有，可以留空或添加默认值
      durations: movie.duration ? [movie.duration] : []
    };

    console.log(`成功获取待映电影详情: ${movie.title}`);
    res.json(formattedMovie);
  } catch (error) {
    console.error('获取待映电影详情失败:', error);
    res.status(500).json({ error: '获取待映电影详情失败', details: error.message });
  }
});

// 6.x 获取评分前十的热映电影
app.get('/api/movies/top-rated', async (req, res) => {
  try {
    // 查询评分前十的热映电影
    const [movies] = await pool.execute(
      `SELECT * FROM movies WHERE average_rating IS NOT NULL ORDER BY average_rating DESC LIMIT 10`
    );
    // 格式化电影数据
    const formattedMovies = movies.map(movie => ({
      id: movie.id,
      title: movie.title,
      original_title: movie.original_title,
      images: {
        large: movie.image_url
      },
      rating: {
        average: parseFloat(movie.average_rating)
      },
      directors: movie.director ? movie.director.split('，').map(d => ({ name: d.trim() })) : [],
      casts: movie.cast ? movie.cast.split('，').map(c => ({ name: c.trim() })) : [],
      genres: String(movie.genres || '').split('，'),
      year: movie.release_date ? movie.release_date.substring(0, 4) : '',
      summary: movie.summary
    }));
    res.json(formattedMovies);
  } catch (error) {
    console.error('获取评分前十热映电影失败:', error);
    res.status(500).json({ error: '获取评分前十热映电影失败', details: error.message });
  }
});

// 7. 404 处理
app.use((req, res) => {
  console.log('404 - 未找到路由:', req.method, req.url);
  res.status(404).json({ error: '未找到请求的资源' });
});

// 8. 错误处理
app.use((err, req, res, next) => {
  console.error('服务器错误:', err);
  res.status(500).json({ error: '服务器内部错误' });
});

// 9. 启动服务器
const PORT = process.env.PORT || 3001;
const server = app.listen(PORT, '0.0.0.0', () => {
  console.log('----------------------------------------');
  console.log(`服务器启动成功！`);
  console.log(`监听端口: ${PORT}`);
  console.log(`可以通过以下地址访问：`);
  console.log(`- http://localhost:${PORT}`);
  console.log(`- http://127.0.0.1:${PORT}`);
  console.log(`- http://192.168.38.18:${PORT}`);
  console.log('----------------------------------------');
});

// 10. 服务器错误处理
server.on('error', (error) => {
  console.error('服务器错误:', error);
  if (error.code === 'EADDRINUSE') {
    console.error(`端口 ${PORT} 已被占用`);
  }
}); 